package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
     @Autowired
     private EmpService empService;



    @Override
    public PageResult getClazz(String name, LocalDate begin, LocalDate end, int page, int pageSize) {

          Page<Clazz> pageInfo = new Page<>(page,pageSize);
          pageInfo = lambdaQuery().like(Clazz::getName, name)
                     .between(begin != null && end != null, Clazz::getEndDate, begin, end).page(pageInfo);
          List<Clazz> clazzs = pageInfo.getRecords();
          LocalDate now = LocalDate.now();
          clazzs.forEach( clazz ->{
              if(now.isBefore(clazz.getEndDate()) && now.isAfter(clazz.getBeginDate())) {
                  clazz.setStatus("已开班");
              }else if (now.isBefore(clazz.getBeginDate())){
                  clazz.setStatus("未开班");
              }else{
                  clazz.setStatus("已结课");
              }
          });
          List<Integer> masterIds = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
          if(!masterIds.isEmpty()){
             List<Emp> emps = empService.listByIds(masterIds);
             clazzs.forEach( clazz ->{
                 emps.forEach(emp ->{
                     if(emp !=null && emp.getId().equals(clazz.getMasterId())){
                         clazz.setMasterName(emp.getName());
                     }
                 });
             });
         }
        return new PageResult(pageInfo.getTotal(), clazzs);
    }
}
